package netw;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import entity.characters.Player;

public class Transmitter extends Thread {
	
	DatagramSocket clientSocket;
	InetAddress IPAddress;
	Player player = null;
	
	public Transmitter(Player player) {
		try {
			this.player = player;
			
			clientSocket = new DatagramSocket();
			IPAddress = InetAddress.getByName("localhost");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public void run() {
		while(player != null) {
			transmitPlayerLocation(player);
			try {
				Thread.sleep(1000 / 30/*packets per second*/);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void transmitPlayerLocation(Player player) {
		try {
			Message m = new Message(
					player.getPosition().x,
					player.getPosition().y,
					player.getPosition().z,
					player.getRotation().x,
					player.getRotation().y,
					player.getRotation().z
					);
			
			ByteArrayOutputStream bStream = new ByteArrayOutputStream();
			ObjectOutput oo = new ObjectOutputStream(bStream);
			oo.writeObject(m);
			oo.close();
			
			byte[] data = bStream.toByteArray();
			//System.out.println("byte array length = " + data.length);
			
			DatagramPacket sendPacket = new DatagramPacket(data, data.length, IPAddress, 9876);
			clientSocket.send(sendPacket);
			
			//clientSocket.close();
			
			System.out.println("transmitted: " + m);
			
		} catch (Exception e) {
			clientSocket.close();
			e.printStackTrace();
		}
	}
}
